#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/select.h>
#include <sys/epoll.h>
#include <poll.h>
#include <sys/types.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

#define MAX 4096

const int gdefalutfd = -1;

class EpollServer
{
    static const int revs_num = 64;
public:
    EpollServer(uint16_t newport)
        : _port(newport), 
        _listen_socket(std::make_unique<TcpSocket>()), 
        _is_running(false),
        _epfd(gdefalutfd)
    {
    }

    void Init()
    {
        _listen_socket->BulidTcpSocket(_port);
        // 1.创建epoll模型
        _epfd = epoll_create(256);
        if(_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::DEBUG) << "epoll_create success" << _epfd;

        // 2. 至少要将listensock
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_socket->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->Fd(), &ev);
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            exit(EPOLL_CTL_ERR);
        }
    }

    void Start()
    {
        int timeout = -1;
        _is_running = true;
        while (_is_running)
        {
            // poll等待
            int n = epoll_wait(_epfd, _revs, revs_num, timeout);
            switch (n)
            {
            case 0:
                std::cout << "select timeout" << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                // 有事件就绪
                std::cout << "有事件就绪: " << std::endl;
                Dispatcher(n);
                break;
            }

        }
        _is_running = false;
    }

    void Accept()
    {
        InetAddr client;
        int newfd = _listen_socket->Acceptor(&client); //accept不会被阻塞
        if (newfd < 0)
            return;
        else
        {
            std::cout << "获得了一个新的连接: " << newfd << ", new client: " << client.Addr() << std::endl;
            // 我们需要将这个新的newfd添加到epoll，让epoll帮我们进行监管
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = newfd;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                close(newfd);
                exit(EPOLL_CTL_ERR);
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success, fd: " << newfd;
        }
    }

    void Recver(int fd)
    {
        // 处理读事件
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << "client# " << buffer << std::endl;
            // 回显消息
            std::string message = "ehco# ";
            message += buffer;
            send(fd, message.c_str(), message.size(), 0); // bug
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出链接, sockfd: " << fd;
            // 把fd从epoll中删除，必须保证fd是一个合法的fd
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            // 必须先在epoll中删除，再关闭fd
            close(fd);
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取链失败, sockfd: " << fd;
            // 把fd从epoll中删除，必须保证fd是一个合法的fd  
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            close(fd);
        }

    }

    void Dispatcher(int num) // rfds就可能会有更多fd就绪
    {
        for (int i = 0; i < num; i++)
        {
            int events = _revs[i].events;
            int fd = _revs[i].data.fd;
            if(fd == _listen_socket->Fd())
            {
                if(events & EPOLLIN)
                {
                    // listen sock fd 就绪
                    Accept();
                }
            }
            else
            {
                // 普通文件符就绪
                if(events & EPOLLIN)
                {
                    // 读事件就绪
                    Recver(fd);
                }
                // else if(events & EPOLLOUT)
                // {
                //     // 写事件就绪
                // }
            }
        }
    }

    ~EpollServer()
    {
        _listen_socket->Close();
        if(_epfd >= 0)
            ::close(_epfd);
        
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _is_running;
    int _epfd;
    struct epoll_event _revs[revs_num];
};